﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Clandestine.Battle.Effects
{
    public static class BattleEffects
    {
        private static Dictionary<string, BattleEffect> effects = new Dictionary<string, BattleEffect>();

        /// <summary>
        /// Applies a battle effect to a specific target.
        /// </summary>
        /// <param name="name">The name of the effect to apply.</param>
        /// <param name="target">The target to apply the effect to.</param>
        public static void DoEffect(string name, Combatant source, Combatant target)
        {
            BattleEffects.DoEffect(name, source, new Combatant[] { target });
        }

        /// <summary>
        /// Applies a battle effect to a number of targets.
        /// </summary>
        /// <param name="name">The name of the effect to apply.</param>
        /// <param name="targets">An array of combatants to apply the effect to.</param>
        public static void DoEffect(string name, Combatant source, Combatant[] targets)
        {
            if (effects.ContainsKey(name))
                effects[name].Action(source, targets);
            else
                Log.e("Battle: Tried to do the battle effect {0}, but it was not found. Does it inherit BattleEffect?", name);
        }

        public static void LoadEffects()
        {
            // You do not need to call this, but doing so will cause the constructor to be called ^^
        }

        static BattleEffects()
        {
            Log.i("Battle: Starting to load battle effects...");
            DateTime start = DateTime.Now;

            // Add all classes that inherit BattleEffect
            // Note: Do not make effects in other assemblies without updating this func!
            Type[] types = Assembly.GetExecutingAssembly().GetTypes();
            for (int i = 0; i < types.Length; i++)
            {
                if (types[i].IsSubclassOf(Assembly.GetExecutingAssembly().GetType("Clandestine.Battle.Effects.BattleEffect")))
                {
                    effects.Add(types[i].Name, (BattleEffect)System.Activator.CreateInstance(types[i]));
                    Log.i("Battle: Addeded BattleEffect {0}.", types[i].Name);
                }
            }

            Log.i("Took {0} ticks.", start.Ticks - DateTime.Now.Ticks);
            Log.i("Battle: Finished loading battle effects...");
        }
    }
}
